<?php
declare (strict_types = 1);

namespace app\controller;

use app\model\CollegeModel;
use app\model\GradeModel;
use app\model\UserModel;
use think\facade\Db;
use think\Request;

class College extends Base
{

    //获取所有院校信息数据
    public function getAllCollegeInfo(Request $request){

        $db=new CollegeModel();

        $page= $request->param('page');
        $limit= $request->param('limit');
        $find_provs_key=$request->param('find_provs_key');
        $find_name_key=$request->param('find_name_key');

//        按省份搜索
        if( isset($find_provs_key) && !empty($find_provs_key)){

            $db=$db->where('college_city',$find_provs_key);


            $info=Db::table('college')
                ->alias('a')
                ->where('a.college_city',$find_provs_key)
                ->leftJoin('collect b','a.college_id = b.college_id')
                ->field('a.college_id,a.college_name,a.college_city,a.college_belong,a.college_label,a.college_yz_url,college_gf_url,a.college_img,a.college_info,count(b.user_id) as cnt')
                ->group('a.college_id')
                ->page($page)->limit($limit)->select();


            $total=$db->count('college_id');

        }

//        按院校名称
        else if (isset($find_name_key) && !empty($find_name_key)){

            $db=$db->where('college_name','like','%'.$find_name_key.'%');

            $info=Db::table('college')
              ->alias('a')
              ->where('a.college_name','like','%'.$find_name_key.'%')
              ->leftJoin('collect b','a.college_id = b.college_id')
              ->field('a.college_id,a.college_name,a.college_city,a.college_belong,a.college_label,a.college_yz_url,college_gf_url,a.college_img,a.college_info,count(b.user_id) as cnt')
              ->group('a.college_id')
              ->page($page)->limit($limit)->select();

            $total=$db->count('college_id');

        }

        else{


            $info=Db::table('college')
                ->alias('a')
                ->where('a.college_name','like','%'.$find_name_key.'%')
                ->leftJoin('collect b','a.college_id = b.college_id')
                ->field('a.college_id,a.college_name,a.college_city,a.college_belong,a.college_label,a.college_yz_url,college_gf_url,a.college_img,a.college_info,count(b.user_id) as cnt')
                ->group('a.college_id')
                ->page($page)->limit($limit)->select();

            $total=$db->count('college_id');

        }


        return json(['code'=>1,'data'=>$info,'total'=>$total]);

    }

    //    根据college_id获取院校信息
    public function getColInfoByColID(Request $request){
        $college_id=$request->param('college_id');
        $college=CollegeModel::getColByColId($college_id);
        return json($college);
    }

    // 获取当前登录用户收藏的院校信息
    public function getMyColByUserID(Request $request){
//        parent::initialize();

        $user_id=UserModel::getUseridByToken($request->param(('token'))); //获取用户id

        $db=new CollegeModel();

        $info = $db->table('college a,collect b,user c')
            ->where( 'c.user_id',$user_id)
            ->where('a.college_id = b.college_id and b.user_id=c.user_id')
            ->select();

        $total=$db->table('college a,collect b,user c')
            ->where( 'c.user_id',$user_id)
            ->where('a.college_id = b.college_id and b.user_id=c.user_id')
            ->count('a.college_id');


        return json(['code'=>1,'data'=>$info,'total'=>$total]);

    }

//    取消收藏
    public function cancelCollect(Request $request){

        $college_id= $request->param('college_id');
        $user_id=UserModel::getUseridByToken($request->param(('token'))); //获取用户id

        $res=Db::table('collect')
            ->where('user_id', $user_id)
            ->where('college_id',$college_id)
            ->delete();

        if($res){
            return json(['code'=>1]);
        }else{
            return json(['code'=>0]);
        }
    }

//    根据用户id和院校id查看用户是否收藏该院校
    public function ifCollect(Request $request){

        $college_id= $request->param('college_id');
        $user_id=UserModel::getUseridByToken($request->param(('token'))); //获取用户id

        $res=Db::table('collect')
            ->where('user_id', $user_id)
            ->where('college_id',$college_id)
            ->find();

        if($res){
            return json(['code'=>1]);
        }
        return json(['code'=>0]);

    }
//    添加收藏
    public function addCollect(Request $request){

        $college_id= $request->param('college_id');
        $user_id=UserModel::getUseridByToken($request->param(('token'))); //获取用户id


        $data = ['college_id'=>$college_id,'user_id'=>$user_id];
        $if_add_ok=Db::table('collect')->insert($data);
        if($if_add_ok)
        {
            return json(['code'=>1]);
        }
        return json(['code'=>0]);

    }

//    根据院校id删除院校
    public function deleteCollegeByID(Request $request){


        $college_ids=$request->param('college_id');

        if(is_array($college_ids)){
            foreach ($college_ids as $ids){
                $college= CollegeModel::find($ids);
                $college_img=$college['college_img'];
                $college_img_url= FILEDIR.'college_img/'.$college_img;
                if($college->delete()){
                    if($college_img !='default_college_img.jpg'){
                        if( unlink($college_img_url)) {}
                    }
                }
                else{
                    return json(['code'=>0]);
                }
            }
            return json(['code'=>1]);
        }
        else{

            $college= CollegeModel::find($college_ids);
            $college_img=$college['college_img'];

            $college_img_url= FILEDIR.'college_img/'.$college_img;

            if($college->delete()){
                if($college_img !='default_college_img.jpg'){
                    if( unlink($college_img_url))
                    {
                        //返回消息
                        return json(array(
                            'code' => 1
                        ));
                    }
                }
                //返回消息
                return json(array(
                    'code' => 1
                ));

            }

            return json(array(
                'code' => 0
            ));

        }




//        if(is_array($college_ids)){
//            $condition = 'college_id in('.implode(',',$college_ids).')';
//        }else{
//            $condition = 'college_id='.$college_ids;
//        }
//
//        if($college->where($condition)->delete()){
//            return json(['code'=>1]);
//        }
//


    }

//    根据院校id修改院校信息
     public function updateCollegeInfo(Request $request){
         $college_id=$_POST['college_id'];
         $college_name=$_POST['college_name'];
         $college_info=$_POST['college_info'];
         $college_yz_url=$_POST['college_yz_url'];
         $college_gf_url=$_POST['college_gf_url'];
         $college_city=$_POST['college_city'];
         $college_label=$_POST['college_label'];
         $college_belong=$_POST['college_belong'];


         $college=CollegeModel::find($college_id);
//        旧图片
         $college_img=$college['college_img'];
         $college_img_pth=FILEDIR.'college_img/'.$college_img;

//        没有上传图片
         if($_POST['if_img']==0){

         }
         else{

             if($college_img !='default_college_img.jpg'){
                 if(unlink($college_img_pth))
                 {
                 }
             }
             //上传图片文件
             $colimg=$_FILES['college_img'];
             //将图片存入目录
             $dir_img = FILEDIR.'college_img';

             if(!is_dir($dir_img))
             {
                 mkdir($dir_img, 0777, true);
                 chmod($dir_img, 0777); // 修改文件模式，所有人都有读、写、执行权限
             }
             else{
                 chmod($dir_img, 0777); // 修改文件模式，所有人都有读、写、执行权限
             }

             // 接收图片文件信息
             $img_name = $colimg['name'];

             $img_tmp_name = $colimg['tmp_name']; //储存的临时文件名，一般是系统默认
             $img_ext = pathinfo($img_name, PATHINFO_EXTENSION); // 提取上传文件的扩展名
             // 得到唯一的文件名，防止因文件名相同而产生覆盖
             $college_img = md5(uniqid('',true)).".$img_ext"; // md5加密，uniqid产生唯一id，microtime作前缀
             // 目标存放文件地址
             $img_destination = $dir_img."/".$college_img;
             // 当文件上传成功时，存入临时文件夹，服务器开始判断
             if (@move_uploaded_file($img_tmp_name, $img_destination))
             {
//            @错误抑制符，不让用户看到警告
             }
             else {
                 //echo "文件".$img_tmp_name."上传失败！";
                 //返回消息
                 return json(array(
                     'code' => 0
                 ));
             }
             chmod($img_destination, 0777); // 修改文件模式，所有人都有读、写、执行权限

         }


         $data = [
             'college_name' => $college_name,
             'college_info' => $college_info,
             'college_gf_url' => $college_gf_url,
             'college_yz_url' => $college_yz_url,
             'college_city' => $college_city,
             'college_label' => $college_label,
             'college_type' => $college_belong,
             'college_img' => $college_img,

         ];

         if ($college->save($data)) {
             return json(array(
                 'code' =>1
             ));
         }
         //返回消息
         return json(array(
             'code' => 0
         ));

     }

//     添加院校信息
     public function addCollegeInfo(Request $request){

         $college_name=$_POST['college_name'];
         $college_info=$_POST['college_info'];
         $college_city=$_POST['college_city'];
         $college_label=$_POST['college_label'];
         $college_yz_url=$_POST['college_yz_url'];
         $college_gf_url=$_POST['college_gf_url'];
         $college_belong=$_POST['college_belong'];

         $db=new CollegeModel();
         $if_same_name=$db->where('college_name',$college_name)->find();
//         数据表已存在该院校
         if($if_same_name!=null){
             return json(array(
                 'code' => 2
             ));
         }

         //        没有上传图片
         if($_POST['if_img']==0){
             $college_save_img='default_college_img.jpg';
         }
         else{
//             上传了图片
             //将图片存入目录
             $dir_img = FILEDIR.'college_img';
             $colimg=$_FILES['college_img'];

             if(!is_dir($dir_img))
             {
                 mkdir($dir_img, 0777, true);
                 chmod($dir_img, 0777); // 修改文件模式，所有人都有读、写、执行权限
             }
             else{
                 chmod($dir_img, 0777); // 修改文件模式，所有人都有读、写、执行权限
             }

             // 接收图片文件信息
             $img_name = $colimg['name'];

             $img_tmp_name = $colimg['tmp_name']; //储存的临时文件名，一般是系统默认
             $img_ext = pathinfo($img_name, PATHINFO_EXTENSION); // 提取上传文件的扩展名
             // 得到唯一的文件名，防止因文件名相同而产生覆盖
             $college_save_img = md5(uniqid('',true)).".$img_ext"; // md5加密，uniqid产生唯一id，microtime作前缀
             // 目标存放文件地址
             $img_destination = $dir_img."/".$college_save_img;
             // 当文件上传成功时，存入临时文件夹，服务器开始判断
             if (@move_uploaded_file($img_tmp_name, $img_destination))
             {
//            @错误抑制符，不让用户看到警告
             }
             else {
                 //echo "文件".$img_tmp_name."上传失败！";
                 //返回消息
                 return json(array(
                     'code' => 0
                 ));
             }
             chmod($img_destination, 0777); // 修改文件模式，所有人都有读、写、执行权限
         }


         $data = [
             'college_name' => $college_name,
             'college_info' => $college_info,
             'college_city' => $college_city,
             'college_label' => $college_label,
             'college_yz_url' => $college_yz_url,
             'college_gf_url' => $college_gf_url,
             'college_belong' => $college_belong,
             'college_img'  => $college_save_img
         ];

         $db=new CollegeModel();
         if ($db->save($data)) {
             //返回消息 上传成功
             return json(array(
                 'code' => 1
             ));
         }
         else {
             //返回消息
             return json(array(
                 'code' => 0
             ));
         }


     }

//     根据类别和年份获取分数线
     public function getGradesByYear(Request $request){

         $grades_year=$request->param('grades_year');
         $grades_sort=$request->param('grades_sort');
         $grades=new GradeModel();


         $db=$grades
             ->where('grades_sort',$grades_sort)
             ->where('grades_year',$grades_year)
             ->find();

         return json(['data'=>$db]);

     }

//     获取所有年份
     public function getAllYears(){

         $years=Db::name('grades')->Distinct(true)
             ->field('grades_year')
             ->order('grades_year desc')
             ->select();

         return json(['years'=>$years]);

     }


//     添加分数线
     public function addGrades(Request $request){

         $grades_sort=$_POST['grades_sort'];
         $grades_year=$_POST['grades_year'];
         $grades_img=$_FILES['grades_img'];

         $db=new GradeModel();
         $if_save=$db->where('grades_sort',$grades_sort)
                   ->where('grades_year',$grades_year)
                  ->find();

         if($if_save!=null){
             return json(array(
                 'code' => 2
             ));
         }

         //将图片存入目录
         $dir_img = FILEDIR.'grades_img/'.$grades_year;

         if(!is_dir($dir_img))
         {
             mkdir($dir_img, 0777, true);
             chmod($dir_img, 0777); // 修改文件模式，所有人都有读、写、执行权限
         }
         else{
             chmod($dir_img, 0777); // 修改文件模式，所有人都有读、写、执行权限
         }

         // 接收图片文件信息
         $img_name = $grades_img['name'];

         $img_tmp_name = $grades_img['tmp_name']; //储存的临时文件名，一般是系统默认
         $img_ext = pathinfo($img_name, PATHINFO_EXTENSION); // 提取上传文件的扩展名
         // 得到唯一的文件名，防止因文件名相同而产生覆盖
         $grades_save_img = md5(uniqid('',true)).".$img_ext"; // md5加密，uniqid产生唯一id，microtime作前缀
         // 目标存放文件地址
         $img_destination = $dir_img."/".$grades_save_img;
         // 当文件上传成功时，存入临时文件夹，服务器开始判断
         if (@move_uploaded_file($img_tmp_name, $img_destination))
         {
//            @错误抑制符，不让用户看到警告
         }
         else {
             //echo "文件".$img_tmp_name."上传失败！";
             //返回消息
             return json(array(
                 'code' => 0
             ));
         }
         chmod($img_destination, 0777); // 修改文件模式，所有人都有读、写、执行权限

         $data = [
             'grades_sort' => $grades_sort,
             'grades_year' => $grades_year,
             'grades_img' => $grades_save_img,

         ];

         $db=new GradeModel();
         if ($db->save($data)) {
             //返回消息 上传成功
             return json(array(
                 'code' => 1
             ));
         }
         else {
             //返回消息
             return json(array(
                 'code' => 0
             ));
         }



     }

//     删除分数线信息
     public function deleteGrades(Request $request){

        $grades_sort=$request->param('grades_sort');
        $grades_year=$request->param('grades_year');

         $db=new GradeModel();
         $grade=$db->where('grades_sort',$grades_sort)
             ->where('grades_year',$grades_year)
             ->find();

         if($grade==null){
             return json(array(
                 'code' => 0
             ));
         }

         $grades_id=$grade->grades_id;
         $delete_grades=GradeModel::find($grades_id);

         $grades_img=$grade->grades_img;
         $grades_url= FILEDIR.'grades_img/'.$grades_year.'/'.$grades_img;


         if($delete_grades->delete()){
             if( unlink($grades_url))
             {
                 //返回消息
                 return json(array(
                     'code' => 1
                 ));
             }
         }

         return json(array(
             'code' => 0
         ));




     }





    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }
}
